//
//  PersonOrderListViewController.m
//  TestProject6
//
//  Created by JasonLee on 14/12/11.
//  Copyright (c) 2014年 JasonLee. All rights reserved.
//

#import "PersonCouponListViewController.h"
#import "OrderModel.h"
#import "PersonOrderDetailViewController.h"
#import "ProtocolManager.h"
#import "Common.h"
#import "DVSwitch.h"
#import "TransforController.h"

@interface PersonCouponListViewController ()<UITableViewDataSource, UITableViewDelegate>{
    PullTableView *_tableView;
    NSMutableArray *_order;
    NSMutableArray *_orderCells;
    int currRow;
    UILabel *lbFoundNoOrders;
}
@property (nonatomic,assign) int currentIndex;

@property (nonatomic,strong)NSMutableArray *dataInReturn;

@property (nonatomic, assign) int page_current;

@property (nonatomic, strong) DVSwitch *topSelectMenu;

@end

@implementation PersonCouponListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"childViewControllers:%@", self.navigationController.childViewControllers);
    NSLog(@"Loading PersonCouponListViewController;");
    [self.view setFrame:[UIScreen mainScreen].bounds];
    self.currentIndex = 0;
    self.page_current = 0;
    //[self initData];
    [self setEnableLoadMore:YES];
    self.pullTableViewDelegate = self;
    self.navigationItem.title = @"我的代金券";
    CGRect screenRect = [UIScreen mainScreen].bounds;
    CGSize screenSize = screenRect.size;
    //_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height - 60)];
    self.tableView.frame = CGRectMake(0, HEIGHT_MENU_BAR, screenSize.width, self.view.frame.size.height - HEIGHT_NAVIGATION_BAR - HEIGHT_STATUS_BAR - HEIGHT_MENU_BAR);
    _tableView = self.tableView;
    //NSLog(@"==>>PersonOrderList-->>viewDidLoad||_tableView:%f", _tableView.frame.size.height);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    
    //    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTableviewCellLongPressed:)];
    //    longPress.minimumPressDuration = 1.0;
    //    [_tableView addGestureRecognizer:longPress];
    [self.view addSubview:_tableView];
    UIView *view_navagationBar = [[UIView alloc]initWithFrame:CGRectMake(0, -65, 320, 65)];
    view_navagationBar.backgroundColor = [Common colorWithRGB:0x18aaf6];
    [self.view addSubview:view_navagationBar];
    [self initMenuWithArray];
    //    self.navigationController.navigationBar.backgroundColor  = [Common colorWithRGB:0x18aaf6];
    [self getCouponList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData:(NSArray *)array{
    //NSString *path = [[NSBundle mainBundle] pathForResource:@"PersonOrder" ofType:@"plist"];
    //NSArray *array = [NSArray arrayWithContentsOfFile:path];
    if (_order.count <= 0){
        self->_order = [[NSMutableArray alloc]init];}
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [self->_order addObject:[OrderModel statusWithDictionary:obj]];
        //NSLog(@"==>>PersonOrderList-->>initData||model:%@", [[_order objectAtIndex:idx] getOrder]);
    }];
    //NSLog(@"==>>PersonOrderList-->>initData||_order:%@",_order);
}

- (void)initMenuWithArray{
    if(self.topSelectMenu == nil){
        self.topSelectMenu = [DVSwitch switchWithStringsArray:[NSArray arrayWithObjects:@"全部",@"未使用",@"已使用", @"已过期", nil]];
        self.topSelectMenu.frame = CGRectMake(0, 0, 320, 35);
        self.topSelectMenu.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.sliderColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.labelTextColorInsideSlider = [UIColor colorWithRed:20/255.0 green:180/255.0 blue:220/255.0 alpha:1];
        self.topSelectMenu.labelTextColorOutsideSlider = [UIColor blackColor];
        self.topSelectMenu.cornerRadius = 5;
        [self.topSelectMenu addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.topSelectMenu];
    }
}

- (void)valueChanged:(id)sender{
    DVSwitch* segmentedControl = sender;
    NSLog(@"%s line:%d segment has changed to %d", __FUNCTION__, __LINE__, segmentedControl.
          selectedIndex);
    
    if(self.page_current != segmentedControl.selectedIndex){
        self.page_current = segmentedControl.selectedIndex;
        [self pullTableViewDidTriggerRefresh:self.tableView];
    }
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - Protocol request
- (void)getCouponList
{
    //[[ProtocolManager shareInstance] getStoreType:self selector:@selector(getOrderListCallback:)];
    //    [[ProtocolManager shareInstance] getOrderList:[ProtocolManager shareInstance].loginName pageIndex:[[NSString alloc]initWithFormat:@"%i",_currentIndex + 1] target:self selector:@selector(getOrderListCallback:)];
    [[Common shareInstance]showLoadingViewWithMessage:@"读取中"];
    [[ProtocolManager shareInstance] getCouponListWithStatus:self.page_current andPage:[[NSString alloc]initWithFormat:@"%i",_currentIndex + 1] target:self selector:@selector(getCounponListCallback:)];
    
}

#pragma mark - Protocol call back
- (void)getCounponListCallback:(NSDictionary*)dic
{
    NSLog(@"%s || dic:%@", __FUNCTION__, dic);
    if ((dic[P_RESULT] == [NSNull null]) ) {
        
        [self resetPullTableViewState];
        return;
    }
    if (self.currentIndex == 0) {
        self.dataInReturn = [NSMutableArray array];
    }
    NSArray* orderList;
    if(![[Common valueForKey:P_RESULT dic:dic] isKindOfClass:[NSArray class]]){
        orderList = [[NSArray alloc]init];
    }else{
        orderList = [Common valueForKey:P_RESULT dic:dic];
    }
    if ([orderList isKindOfClass:[NSArray class]]) {
        [self.dataInReturn addObjectsFromArray:orderList];
        self.currentIndex++;
    }
    if(self.dataInReturn.count > 0){
        if (orderList.count < STORE_LIST_RETURN_COUNT) {
            [self setEnableLoadMore:NO];
        }
        else {
            [self setEnableLoadMore:YES];
        }
        //NSLog(@"==>>PersonOrderList-->>getOrderListCallBack||orderList:%@", orderList);
        //NSLog(@"==>>PersonOrderList-->>getOrderListCallBack||dataInReturn:%@", _dataInReturn);
        [self resetPullTableViewState];
        //      if(lbFoundNoOrders != nil){
        [lbFoundNoOrders removeFromSuperview];
    }else{
        if(lbFoundNoOrders == nil){
            lbFoundNoOrders = [[UILabel alloc] initWithFrame:CGRectMake(0, 120, 320, 30)];
            lbFoundNoOrders.textColor = [UIColor grayColor];
            lbFoundNoOrders.text = @"还没有优惠券！";
            lbFoundNoOrders.textAlignment = UITextAlignmentCenter;
            [_tableView.tableFooterView addSubview:lbFoundNoOrders];
            [self setEnableLoadMore:NO];
        }else{
            [_tableView.tableFooterView addSubview:lbFoundNoOrders];
        }
    }
    [[Common shareInstance]stopLoadingView];
    [_tableView reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //NSLog(@"%lu", (unsigned long)_order.count);
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataInReturn.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"OKCoupon" owner:nil options:nil];
    cell= [nibView objectAtIndex:0];
    NSDictionary *dic_temp = [NSDictionary dictionaryWithDictionary:self.dataInReturn[indexPath.row]];
    //    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    UILabel *lb_title = (UILabel *)[cell viewWithTag:90002];
    UILabel *lb_date = (UILabel *)[cell viewWithTag:90006];
    UILabel *lb_end = (UILabel *)[cell viewWithTag:90007];
    UILabel *lb_price = (UILabel *)[cell viewWithTag:900004];
    UILabel *lb_status = (UILabel *)[cell viewWithTag:900005];
    NSString *imgUrl = [Common valueForKey:@"coverPath" dic:dic_temp];
    if([imgUrl isEqualToString:@""] || imgUrl == nil){
    }else{
        UIImageView *img_cover = (UIImageView *)[cell viewWithTag:900001];
        [img_cover setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
    }
    lb_title.text = [Common valueForKey:@"title" dic:dic_temp];
    lb_date.text = [NSString stringWithFormat:@"%@", [Common valueForKey:@"startTime" dic:dic_temp]];
    lb_end.text = [NSString stringWithFormat:@"%@", [Common valueForKey:@"endTime" dic:dic_temp]];
    lb_price.text = [NSString stringWithFormat:@"￥%@",[Common valueForKey:@"cash2" dic:dic_temp]];
    int status = [[Common valueForKey:@"status" dic:dic_temp] intValue];
    NSString *string_temp = nil;
    switch (status) {
        case 0:
        {
            string_temp = @"未激活";
            lb_status.backgroundColor = [UIColor orangeColor];
        }
            break;
        case 1:
        {
            string_temp = @"未使用";
            //            lb_status.backgroundColor
        }
            break;
        case 2:
        {
            string_temp = @"已使用";
            lb_status.backgroundColor = [TransforController getColorWithRGB:0xf27538];
            break;
        }
        case 3:
        {
            string_temp = @"已过期";
            lb_status.backgroundColor = [UIColor redColor];
            break;
        }
        default:
            string_temp = @"";
            break;
    }
    lb_status.text = string_temp;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    OrderModel *orderModel = _order[indexPath.row];
//    PersonOrderDetailViewController *personOrderDetailController = [[PersonOrderDetailViewController alloc]init];
//    personOrderDetailController.model = orderModel;
//    [self.navigationController pushViewController:personOrderDetailController animated:YES];
//}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    self.currentIndex = 0;
    [self setPullTableIsLoadMore:YES];
//    self.dataInReturn
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self getCouponList];
    
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getCouponList];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

@end
